package cc.kzc.adminauth.auth.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson2.JSON;

import cc.kzc.adminauth.auth.service.LoginService;
import cc.kzc.adminauth.auth.vo.UserReq;
import cc.kzc.adminauth.common.BaseResponse;
import cc.kzc.adminauth.common.ErrorCode;
import cc.kzc.adminauth.exception.BaseError;
import cc.kzc.adminauth.misc.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;

@Validated
@Controller
@Slf4j
public class LoginController {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private LoginService loginService;

	@RequestMapping(value = { "/account/login" }, produces = "application/json;charset=UTF-8")
	@ResponseBody()
	public String login(@RequestBody String requestBody) {

		String ip = HttpRequestUtil.getIpAddr(request);
		log.debug("[/account/login][{}]-->{}", ip, requestBody);

		UserReq req = null;
		try {
			req = JSON.parseObject(requestBody, UserReq.class);
		} catch (Exception e) {
			log.error("parse RequestBody json error.", e);
			throw new BaseError(ErrorCode.CLI_PARAM_VALUE_FORMAT_ERR, "json format error");
		}

		BaseResponse resp = loginService.login(req);

		String ret = JSON.toJSONString(resp);
		log.debug(ret);
		return ret;
	}

	@RequestMapping(value = { "/login" }, produces = "application/json;charset=UTF-8")
	@ResponseBody()
	public String login() {
		return "only test login";
	}

}
